package org.feifei.hrm.except;

import org.feifei.hrm.util.AjaxResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author forever
 * @Description: 此处对全局异常进行了处理
 * @date 2022/01/03 18:03
 */
@RestControllerAdvice
public class AllExceptionHandler {

    /**
     *  对业务异常进行全局处理
     * @param e 业务异常
     * @return
     */
    @ExceptionHandler(GlobalException.class)
    public AjaxResult globalExceptionHandler(GlobalException e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setCode(e.getCode()).setMessage(e.getMessage());
    }

    //捕获jsr303参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult exceptionHandle(MethodArgumentNotValidException e){
        e.printStackTrace();
        //获取所有字段错误
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        //遍历所有字段错误进行拼接
        StringBuilder message = new StringBuilder();
        fieldErrors.forEach(fieldError -> {
            message.append(fieldError.getDefaultMessage()+",");
        });
        //去除最后一个逗号
        String str = message.toString();
        str = str.substring(0,str.length()-1);
        return AjaxResult.me().setSuccess(false)
                .setCode(ErrorCode.CODE_400_PARAM_VALID.getCode())
                .setMessage(str);
    }

    /**
     * 对系统异常进行全局处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandle(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false)
                .setCode(ErrorCode.CODE_500_SYSTEM_ERROR.getCode())
                .setMessage(ErrorCode.CODE_500_SYSTEM_ERROR.getMessage());
    }
}
